import React, { createRef } from 'react';
import './css/style.css';
import bg from './img/bg.jpg'

import { apiLogin } from "../../api";

class Login extends React.Component {
  constructor(props) {
    super(props); 
    this.state = {
      username: null,
      password: null
    }
    this.myRef = createRef();
  }
  
  sumibt = (e) => {
    e.preventDefault(); 
    if (this.refs.username.value && this.refs.pwd.value) {
      this.setState(() => {
        return {
          username: this.refs.username.value,
          password: this.refs.pwd.value
        }
      }, () => {
        let { username, password } = this.state
        //axios
        apiLogin({ username, password }).then((res) => {
          
          res.data.code ? alert('密码或者用户名不正确') :this.props.history.push('/main') 
        }).catch(error => console.log(error))
      })
    } else {
      this.refs.username.focus();
    }
  }

  render() {
    return (
      <div>
        <img src={bg} alt="" className="bg"></img>
        <div className="htmleaf-container">
          <div className="wrappers">
            <div className="container">
              <h1>登录</h1>
              <form className="form" onSubmit={this.sumibt}>
                <input ref="username" type="text" id="username" placeholder="用户名" autoComplete="off" />
                <input ref="pwd" type="password" id="pw" placeholder="密码" />
                <button ref={this.myRef} type="sumbit" id="login-button">登录</button>
              </form>
              
            </div>
            <ul className="bg-bubbles">
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
            </ul>
          </div>
        </div>
      </div>
    );
  }
}

export default Login;